/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.liangjun.treatmentbefore.service.impl;

import me.liangjun.drug.domain.DrugDetails;
import me.liangjun.drug.repository.DrugDetailsRepository;
import me.liangjun.drug.service.dto.DrugDetailsDto;
import me.liangjun.drug.service.mapstruct.DrugDetailsMapper;
import me.liangjun.treatmentbefore.domain.TreatmentBeforeEnrollment;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.liangjun.treatmentbefore.repository.TreatmentBeforeEnrollmentRepository;
import me.liangjun.treatmentbefore.service.TreatmentBeforeEnrollmentService;
import me.liangjun.treatmentbefore.service.dto.TreatmentBeforeEnrollmentDto;
import me.liangjun.treatmentbefore.service.dto.TreatmentBeforeEnrollmentQueryCriteria;
import me.liangjun.treatmentbefore.service.mapstruct.TreatmentBeforeEnrollmentMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wei
* @date 2021-09-04
**/
@Service
@RequiredArgsConstructor
public class TreatmentBeforeEnrollmentServiceImpl implements TreatmentBeforeEnrollmentService {

    private final TreatmentBeforeEnrollmentRepository treatmentBeforeEnrollmentRepository;
    private final DrugDetailsRepository drugDetailsRepository;
    private final TreatmentBeforeEnrollmentMapper treatmentBeforeEnrollmentMapper;
    private final DrugDetailsMapper drugDetailsMapper;

    @Override
    public Map<String,Object> queryAll(TreatmentBeforeEnrollmentQueryCriteria criteria, Pageable pageable){
        Page<TreatmentBeforeEnrollment> page = treatmentBeforeEnrollmentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(treatmentBeforeEnrollmentMapper::toDto));
    }

    @Override
    public List<TreatmentBeforeEnrollmentDto> queryAll(TreatmentBeforeEnrollmentQueryCriteria criteria){
        return treatmentBeforeEnrollmentMapper.toDto(treatmentBeforeEnrollmentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public TreatmentBeforeEnrollmentDto findById(Long id) {
        TreatmentBeforeEnrollment treatmentBeforeEnrollment = treatmentBeforeEnrollmentRepository.findById(id).orElseGet(TreatmentBeforeEnrollment::new);
        ValidationUtil.isNull(treatmentBeforeEnrollment.getPId(),"TreatmentBeforeEnrollment","id",id);
        return treatmentBeforeEnrollmentMapper.toDto(treatmentBeforeEnrollment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TreatmentBeforeEnrollmentDto create(TreatmentBeforeEnrollmentDto resources) {
        TreatmentBeforeEnrollment treatmentBeforeEnrollment = treatmentBeforeEnrollmentRepository.findByPId(resources.getPId());
        if (treatmentBeforeEnrollment != null) {
            treatmentBeforeEnrollment.copy(treatmentBeforeEnrollmentMapper.toEntity(resources));
        } else {
            treatmentBeforeEnrollment = treatmentBeforeEnrollmentMapper.toEntity(resources);
        }
        List<DrugDetailsDto> drugDetailsDtos = resources.getMedicals();
        List<DrugDetails> drugDetails = drugDetailsMapper.toEntity(drugDetailsDtos);
        List<DrugDetails> addList = new ArrayList<>();
        for (DrugDetails drugDetail : drugDetails) {
            List<String> mgTreatment = resources.getMgTreatment();
            if (mgTreatment.contains(drugDetail.getDId().toString())) {
                DrugDetails olddrugDetails = drugDetailsRepository.findOne(drugDetail.getPId(), drugDetail.getDId());
                if(olddrugDetails!=null){
                    olddrugDetails.copy(drugDetail);
                    drugDetailsRepository.save(olddrugDetails);
                }else {
                    drugDetailsRepository.save(drugDetail);
                }
                addList.add(drugDetail);
            }
        }
        treatmentBeforeEnrollmentRepository.save(treatmentBeforeEnrollment);
        return treatmentBeforeEnrollmentMapper.domain2Dto(treatmentBeforeEnrollment, addList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TreatmentBeforeEnrollment resources) {
        TreatmentBeforeEnrollment treatmentBeforeEnrollment = treatmentBeforeEnrollmentRepository.findById(resources.getPId()).orElseGet(TreatmentBeforeEnrollment::new);
        ValidationUtil.isNull( treatmentBeforeEnrollment.getPId(),"TreatmentBeforeEnrollment","id",resources.getPId());
        treatmentBeforeEnrollment.copy(resources);
        treatmentBeforeEnrollmentRepository.save(treatmentBeforeEnrollment);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            treatmentBeforeEnrollmentRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TreatmentBeforeEnrollmentDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TreatmentBeforeEnrollmentDto treatmentBeforeEnrollment : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("入組前是否接受治療", treatmentBeforeEnrollment.getState());
            map.put("用药", treatmentBeforeEnrollment.getMgTreatment());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public TreatmentBeforeEnrollmentDto findByPid(Long pid) {
        TreatmentBeforeEnrollment treatmentBeforeEnrollment = treatmentBeforeEnrollmentRepository.findByPId(pid);
        List<DrugDetails> detailsList = drugDetailsRepository.findByPid(pid);
        return treatmentBeforeEnrollmentMapper.domain2Dto(treatmentBeforeEnrollment, detailsList);
    }
}